package com.dongdong.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.dongdong.service.SendSmsService;
import com.dongdong.utils.Result;
import com.dongdong.utils.SMSVO;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class SendSmsServiceImpl implements SendSmsService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SMSVO smsvo;
    @Override
    public Result getCode(String phone) {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(smsvo.getAccessKeyId())
                .accessKeySecret(smsvo.getAccessKeySecret())
                .build());

        AsyncClient client = AsyncClient.builder()
                .region(smsvo.getRegion())
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(smsvo.getEndpointOverride())
                )
                .build();


        String randomCode = RandomUtil.randomNumbers(6);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", randomCode);
        String code = JSONObject.toJSONString(jsonObject);

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(smsvo.getSignName())
                .templateCode(smsvo.getTemplateCode())
                .phoneNumbers(phone)
                .templateParam(code)
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(new Gson().toJson(resp));

        client.close();
        redisTemplate.opsForValue().set("donhdongshop:sms"+phone,randomCode,5, TimeUnit.MINUTES);
        return Result.OK();
    }
}
